/**
 * 自媒体账号状态管理
 *
 * 使用 Zustand 管理自媒体账号的全局状态，包括：
 * - 当前激活账号
 * - 账号列表
 * - 账号记忆和偏好设置
 * - 账号切换和管理
 */

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import type {
  SocialAccount,
  SocialAccountWithDetails,
  AccountMemory,
  AccountPreferences,
  CreateSocialAccountRequest,
  UpdateSocialAccountRequest,
  UpdateAccountMemoryRequest,
  UpdateAccountPreferencesRequest,
} from '../types/socialAccount';
import { socialAccountApi } from '../api';
import { useToastStore } from './toastStore';

interface SocialAccountState {
  // 状态数据
  accounts: SocialAccount[];
  activeAccount: SocialAccountWithDetails | null;
  accountMemories: Record<string, AccountMemory>;
  accountPreferences: Record<string, AccountPreferences>;
  loading: boolean;
  error: string | null;

  // Actions
  loadAccounts: () => Promise<void>;
  createAccount: (data: CreateSocialAccountRequest) => Promise<void>;
  updateAccount: (id: string, data: UpdateSocialAccountRequest) => Promise<void>;
  deleteAccount: (id: string) => Promise<void>;
  activateAccount: (id: string) => Promise<void>;

  // 记忆管理
  loadAccountMemory: (accountId: string) => Promise<void>;
  updateAccountMemory: (accountId: string, data: UpdateAccountMemoryRequest) => Promise<void>;
  resetAccountMemory: (accountId: string) => Promise<void>;

  // 偏好设置
  loadAccountPreferences: (accountId: string) => Promise<void>;
  updateAccountPreferences: (
    accountId: string,
    data: UpdateAccountPreferencesRequest
  ) => Promise<void>;
  resetAccountPreferences: (accountId: string) => Promise<void>;

  // 辅助方法
  getAccountById: (id: string) => SocialAccount | undefined;
  getAccountMemory: (accountId: string) => AccountMemory | undefined;
  getAccountPreferences: (accountId: string) => AccountPreferences | undefined;
  clearError: () => void;
}

export const useSocialAccountStore = create<SocialAccountState>()(
  subscribeWithSelector((set, get) => ({
    // 初始状态
    accounts: [],
    activeAccount: null,
    accountMemories: {},
    accountPreferences: {},
    loading: false,
    error: null,

    // 加载账号列表
    loadAccounts: async () => {
      set({ loading: true, error: null });
      try {
        const response = await socialAccountApi.list();
        const accounts = response.rows || [];

        // 如果没有激活账号，尝试获取当前激活账号
        const currentState = get();
        if (!currentState.activeAccount && accounts.length > 0) {
          try {
            const activeAccount = await socialAccountApi.getActive();
            set({ accounts, activeAccount, loading: false });
          } catch {
            // 如果没有激活账号，设置第一个为激活账号
            const firstAccount = accounts[0];
            if (firstAccount) {
              try {
                await socialAccountApi.activate(firstAccount.id);
                const activeAccount = await socialAccountApi.get(firstAccount.id);
                set({ accounts, activeAccount, loading: false });
              } catch (error) {
                set({ accounts, loading: false, error: `激活账号失败: ${error}` });
              }
            } else {
              set({ accounts, loading: false });
            }
          }
        } else {
          set({ accounts, loading: false });
        }
      } catch (error) {
        set({
          loading: false,
          error: `加载账号列表失败: ${error instanceof Error ? error.message : '未知错误'}`,
        });
        useToastStore.getState().addToast({
          type: 'error',
          message: '加载账号列表失败',
        });
      }
    },

    // 创建账号
    createAccount: async (data: CreateSocialAccountRequest) => {
      set({ loading: true, error: null });
      try {
        const newAccount = await socialAccountApi.create(data);
        const accounts = [...get().accounts, newAccount];

        // 如果这是第一个账号，自动激活
        if (accounts.length === 1) {
          await socialAccountApi.activate(newAccount.id);
          const activeAccount = await socialAccountApi.get(newAccount.id);
          set({ accounts, activeAccount, loading: false });
        } else {
          set({ accounts, loading: false });
        }

        useToastStore.getState().addToast({
          type: 'success',
          message: `账号 "${data.name}" 创建成功`,
        });
      } catch (error) {
        set({
          loading: false,
          error: `创建账号失败: ${error instanceof Error ? error.message : '未知错误'}`,
        });
        useToastStore.getState().addToast({
          type: 'error',
          message: '创建账号失败',
        });
        throw error;
      }
    },

    // 更新账号
    updateAccount: async (id: string, data: UpdateSocialAccountRequest) => {
      set({ loading: true, error: null });
      try {
        const updatedAccount = await socialAccountApi.update(id, data);
        const accounts = get().accounts.map(account =>
          account.id === id ? updatedAccount : account
        );

        // 如果更新的是激活账号，同步更新激活账号信息
        const activeAccount = get().activeAccount;
        if (activeAccount && activeAccount.id === id) {
          const fullAccount = await socialAccountApi.get(id);
          set({ accounts, activeAccount: fullAccount, loading: false });
        } else {
          set({ accounts, loading: false });
        }

        useToastStore.getState().addToast({
          type: 'success',
          message: '账号更新成功',
        });
      } catch (error) {
        set({
          loading: false,
          error: `更新账号失败: ${error instanceof Error ? error.message : '未知错误'}`,
        });
        useToastStore.getState().addToast({
          type: 'error',
          message: '更新账号失败',
        });
        throw error;
      }
    },

    // 删除账号
    deleteAccount: async (id: string) => {
      const account = get().getAccountById(id);
      if (!account) return;

      set({ loading: true, error: null });
      try {
        await socialAccountApi.delete(id);
        const accounts = get().accounts.filter(account => account.id !== id);

        // 如果删除的是激活账号，需要选择新的激活账号
        const activeAccount = get().activeAccount;
        if (activeAccount && activeAccount.id === id) {
          if (accounts.length > 0) {
            await socialAccountApi.activate(accounts[0].id);
            const newActiveAccount = await socialAccountApi.get(accounts[0].id);
            set({ accounts, activeAccount: newActiveAccount, loading: false });
          } else {
            set({ accounts, activeAccount: null, loading: false });
          }
        } else {
          set({ accounts, loading: false });
        }

        // 清理相关的记忆和偏好数据
        const memories = { ...get().accountMemories };
        const preferences = { ...get().accountPreferences };
        delete memories[id];
        delete preferences[id];
        set({ accountMemories: memories, accountPreferences: preferences });

        useToastStore.getState().addToast({
          type: 'success',
          message: `账号 "${account.name}" 删除成功`,
        });
      } catch (error) {
        set({
          loading: false,
          error: `删除账号失败: ${error instanceof Error ? error.message : '未知错误'}`,
        });
        useToastStore.getState().addToast({
          type: 'error',
          message: '删除账号失败',
        });
        throw error;
      }
    },

    // 激活账号
    activateAccount: async (id: string) => {
      const account = get().getAccountById(id);
      if (!account) return;

      set({ loading: true, error: null });
      try {
        await socialAccountApi.activate(id);
        const activeAccount = await socialAccountApi.get(id);
        set({ activeAccount, loading: false });

        useToastStore.getState().addToast({
          type: 'success',
          message: `已切换到账号 "${account.name}"`,
        });
      } catch (error) {
        set({
          loading: false,
          error: `激活账号失败: ${error instanceof Error ? error.message : '未知错误'}`,
        });
        useToastStore.getState().addToast({
          type: 'error',
          message: '激活账号失败',
        });
        throw error;
      }
    },

    // 加载账号记忆
    loadAccountMemory: async (accountId: string) => {
      try {
        const memory = await socialAccountApi.memory.get(accountId);
        set({
          accountMemories: { ...get().accountMemories, [accountId]: memory },
        });
      } catch (error) {
        console.warn(`加载账号记忆失败: ${error}`);
      }
    },

    // 更新账号记忆
    updateAccountMemory: async (accountId: string, data: UpdateAccountMemoryRequest) => {
      try {
        const updatedMemory = await socialAccountApi.memory.update(accountId, data);
        set({
          accountMemories: { ...get().accountMemories, [accountId]: updatedMemory },
        });

        useToastStore.getState().addToast({
          type: 'success',
          message: '账号记忆更新成功',
        });
      } catch (error) {
        useToastStore.getState().addToast({
          type: 'error',
          message: '账号记忆更新失败',
        });
        throw error;
      }
    },

    // 重置账号记忆
    resetAccountMemory: async (accountId: string) => {
      try {
        await socialAccountApi.memory.reset(accountId);
        const memories = { ...get().accountMemories };
        delete memories[accountId];
        set({ accountMemories: memories });

        useToastStore.getState().addToast({
          type: 'success',
          message: '账号记忆重置成功',
        });
      } catch (error) {
        useToastStore.getState().addToast({
          type: 'error',
          message: '账号记忆重置失败',
        });
        throw error;
      }
    },

    // 加载账号偏好
    loadAccountPreferences: async (accountId: string) => {
      try {
        const preferences = await socialAccountApi.preferences.get(accountId);
        set({
          accountPreferences: { ...get().accountPreferences, [accountId]: preferences },
        });
      } catch (error) {
        console.warn(`加载账号偏好失败: ${error}`);
      }
    },

    // 更新账号偏好
    updateAccountPreferences: async (accountId: string, data: UpdateAccountPreferencesRequest) => {
      try {
        const updatedPreferences = await socialAccountApi.preferences.update(accountId, data);
        set({
          accountPreferences: { ...get().accountPreferences, [accountId]: updatedPreferences },
        });

        useToastStore.getState().addToast({
          type: 'success',
          message: '账号偏好更新成功',
        });
      } catch (error) {
        useToastStore.getState().addToast({
          type: 'error',
          message: '账号偏好更新失败',
        });
        throw error;
      }
    },

    // 重置账号偏好
    resetAccountPreferences: async (accountId: string) => {
      try {
        await socialAccountApi.preferences.reset(accountId);
        const preferences = { ...get().accountPreferences };
        delete preferences[accountId];
        set({ accountPreferences: preferences });

        useToastStore.getState().addToast({
          type: 'success',
          message: '账号偏好重置成功',
        });
      } catch (error) {
        useToastStore.getState().addToast({
          type: 'error',
          message: '账号偏好重置失败',
        });
        throw error;
      }
    },

    // 辅助方法
    getAccountById: (id: string) => {
      return get().accounts.find(account => account.id === id);
    },

    getAccountMemory: (accountId: string) => {
      return get().accountMemories[accountId];
    },

    getAccountPreferences: (accountId: string) => {
      return get().accountPreferences[accountId];
    },

    clearError: () => {
      set({ error: null });
    },
  }))
);

// 监听器：当激活账号改变时，自动加载相关数据
useSocialAccountStore.subscribe(
  state => state.activeAccount,
  activeAccount => {
    if (activeAccount) {
      const store = useSocialAccountStore.getState();
      store.loadAccountMemory(activeAccount.id);
      store.loadAccountPreferences(activeAccount.id);
    }
  }
);

// 导出便捷 hooks
export const useActiveAccount = () => {
  const activeAccount = useSocialAccountStore(state => state.activeAccount);
  return activeAccount;
};

export const useAccountMemory = (accountId?: string) => {
  return useSocialAccountStore(state => (accountId ? state.getAccountMemory(accountId) : null));
};

export const useAccountPreferences = (accountId?: string) => {
  return useSocialAccountStore(state =>
    accountId ? state.getAccountPreferences(accountId) : null
  );
};
